package com.bgds.sys.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bgds.sys.api.bean.mars.vo.WaveDataVO;
import com.bgds.sys.api.bean.mos.dto.*;
import com.bgds.sys.api.feign.MosHttpClient;
import com.bgds.sys.api.service.RongZhiService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: warm
 * @Description:
 * @Date: 2020/7/29 14:48
 * @Version: 1.0
 */
@Service
public class RongZhiServiceImpl implements RongZhiService {


    @Override
    public List<MosDeviceDto> getMosDevicesTree() {
        Map<String,String> params=new HashMap<>(10);
        List<MosDeviceDto> devices=new ArrayList<>();
        try {
          String result=  MosHttpClient.doGet(params,"Devicelist");
          devices= JSONArray.parseArray(result, MosDeviceDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return devices;
    }

    /**
     * 资产
     * @return
     */
    @Override
    public List<MosDeviceDto> getAllAssets() {
        Map<String,String> params=new HashMap<>(1);
        List<MosDeviceDto> assetsDtos=new ArrayList<>();
        try {
            String result=  MosHttpClient.doGet(params,"Assets");
            assetsDtos= JSONArray.parseArray(result, MosDeviceDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return assetsDtos;
    }

    /**
     * 获取测量定义趋势数据
     * @param measfId 测量定义ID（资产中type=10,11的为测量定义）
     * @param minDate
     * @param maxDate
     * @param limit
     * @return
     */
    @Override
    public List<VibdatasDto> getVibdatasByParams(String measfId, String minDate, String maxDate, Integer limit) {
        Map<String,String> params=new HashMap<>(3);
        if(StringUtils.isBlank(minDate)){
            params.put("MinDate","");
        }else{
            params.put("MinDate",minDate);
        }
        if(StringUtils.isBlank(maxDate)){
            params.put("MaxDate","");
        }else{
            params.put("MaxDate",maxDate);
        }
        params.put("Limit",limit+"");

        List<VibdatasDto> vibdatas=new ArrayList<>();
        StringBuilder sb=new StringBuilder("Vibdatas/");
        sb.append(measfId);
        try {
            String result=  MosHttpClient.doGet(params,sb.toString());
            vibdatas= JSONArray.parseArray(result, VibdatasDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return vibdatas;

    }

    /**
     * 获取原始波形
     * @param waveKey 测量定义 波形数据key 唯一标识
     * @return
     *  http://127.0.0.1:8125/api/EPMMOS/OriginalWave/{WaveKey}
     *
     */
    @Override
    public List<Float> getOriginalWave(String waveKey) {
        List<Float> floats=new ArrayList<>();
        StringBuilder sb=new StringBuilder("OriginalWave/");
        sb.append(waveKey);
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            floats= JSONArray.parseArray(result, Float.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return floats;
    }

    /**
     * 通道温度
     * @param pointId 测点ID
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @param limit 返回的数量限制,limit 一次最多返回2000条
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/V2/CHTemperatures/{PointId}?MinDate={MinDate}&MaxDate={MaxDate}&Limit={Limit}
     */
    @Override
    public TechniqueDto getChTemperatures(String pointId, String minDate, String maxDate, Integer limit) {
        Map<String,String> parmasMap=new HashMap<>(2);
        parmasMap.put("MinDate",minDate);
        parmasMap.put("MaxDate",maxDate);
        TechniqueDto techniqueDto=null;
        StringBuilder sb=new StringBuilder("CHTemperatures/");
        sb.append(pointId);
        try {
            String result=  MosHttpClient.doGet(parmasMap,sb.toString());
            techniqueDto= JSON.parseObject(result, TechniqueDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return techniqueDto;
    }

    /**
     * 频谱
     * @param waveKey 测量定义 波形数据key 唯一标识
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/Spectrum/{WKey}
     */
    @Override
    public List<WaveDataVO> getSpectrumByWaveKey(String waveKey) {
        WaveFromDto waveFromDto=new WaveFromDto();
        StringBuilder sb=new StringBuilder("Spectrum/");
        sb.append(waveKey);
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            waveFromDto= JSON.parseObject(result, WaveFromDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  processData(waveFromDto);
    }

    /**
     * 倒谱
     * @param waveKey 测量定义 波形数据key 唯一标识
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/Cepstrum/{WKey}
     */
    @Override
    public List<WaveDataVO> getCepstrumByWaveKey(String waveKey) {
        WaveFromDto waveFromDto=new WaveFromDto();
        StringBuilder sb=new StringBuilder("Cepstrum/");
        sb.append(waveKey);
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            waveFromDto= JSON.parseObject(result, WaveFromDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  processData(waveFromDto);
    }

    /**
     * 包络谱
     * @param waveKey 测量定义 波形数据key 唯一标识
     * @param centerRate (必填):中心频率
     * @param bindWidth (必填):带宽
     * @param widthRate (必填):带宽倍数
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/Envolope/{WKey}/{CenterRate}/{BindWidth}/{WidthRate
     */
    @Override
    public List<WaveDataVO> getEnvolopeByWaveKey(String waveKey, Integer centerRate, Integer bindWidth, Integer widthRate) {
        WaveFromDto waveFromDto=null;
        StringBuilder sb=new StringBuilder("Envolope/");
        sb.append(waveKey).append("/").
                append(centerRate+"").append("/").
                append(bindWidth+"").append("/").
                append(widthRate+"");
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            waveFromDto= JSON.parseObject(result, WaveFromDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  processData(waveFromDto);
    }

    /**
     * 振动波形
     * @param waveKey 测量定义 波形数据key 唯一标识
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/VibWave/{WKey}
     */

    @Override
    public List<WaveDataVO> getVibWaveByWaveKey(String waveKey) {
        WaveFromDto waveFromDto=new WaveFromDto();
        StringBuilder sb=new StringBuilder("VibWave/");
        sb.append(waveKey);
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            waveFromDto= JSON.parseObject(result, WaveFromDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return   processData(waveFromDto);
    }

    /**
     * 获取设备或测点最新的采集数据
     * @param deviceIdOrPointId 设备或监测点id
     * @param dateType 采集的数据类型,字符串类型,可是"vib"(振动)或者"temp"(温度),不支持其他类型
     * @return
     *  http://127.0.0.1:8125/api/EPMMOS/GetLastMeasurement/{DeviceIdOrPointId}/{DataType}
     */
    @Override
    public List<JSONObject> getLastMeasurement(String deviceIdOrPointId, String dateType) {
        List<JSONObject> jsonObjects=null;
        StringBuilder sb=new StringBuilder("GetLastMeasurement/");
        sb.append(deviceIdOrPointId).append("/").append(dateType);
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            jsonObjects= JSON.parseArray(result, JSONObject.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObjects;
    }

    /**
     * 获取设备时间区间内的振动读数 开始时间和结束时间距离不能超过1天 最大限制2000条
     * @param deviceId
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @return
     *  http://127.0.0.1:8125/api/EPMMOS/GetMeasurementByPeriod/{DeviceId}?MinDate={MinDate}&MaxDate={MaxDate}
     */
    @Override
    public MeasurementDto getMeasurementByPeriod(String deviceId, String minDate, String maxDate) {
        Map<String,String> parmasMap=new HashMap<>(2);
        parmasMap.put("MinDate",minDate);
        parmasMap.put("MaxDate",maxDate);
        MeasurementDto measurementDto=null;
        StringBuilder sb=new StringBuilder("GetMeasurementByPeriod/");
        sb.append(deviceId);
        try {
            String result=  MosHttpClient.requestGet(parmasMap,sb.toString());
            measurementDto= JSON.parseObject(result, MeasurementDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return measurementDto;
    }

    /**
     * 获取振动采样值指标趋势数据
     * @param pointId ：测点ID
     * @param indexCode ：指标编码
     * @param minDate :开始时间
     * @param maxDate ：结束时间
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/VibSamplingDatas/{PointID}/{indexCode}?MinDate={MinDate}&MaxDate={MaxDate}
     */
    @Override
    public VibSamplingDataDto getVibSamplingDatas(String pointId, String indexCode, String minDate, String maxDate) {
        Map<String,String> parmasMap=new HashMap<>(2);
        parmasMap.put("MinDate",minDate);
        parmasMap.put("MaxDate",maxDate);
        VibSamplingDataDto vibSamplingDataDto=null;
        StringBuilder sb=new StringBuilder("VibSamplingDatas/");
        sb.append(pointId).append("/").append(indexCode);
        try {
            String result=  MosHttpClient.requestGet(parmasMap,sb.toString());
            vibSamplingDataDto= JSON.parseObject(result, VibSamplingDataDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return vibSamplingDataDto;
    }

    /**
     * 工艺数据
     * @param assetid 测点ID
     * @param isOriginalData 是否是取原始数据 0-否 1-是，时间间隔不得大于2天，当获取原始数据数据比较所以建议按照小时或者天获取
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/V2/TSDatas/{assetid}/{IsOriginalData}?MinDate={MinDate}&MaxDate={MaxDate}
     */
    @Override
    public TechniqueDto getTsDatas(String assetid, Integer isOriginalData, String minDate, String maxDate) {
        Map<String,String> parmasMap=new HashMap<>(2);
        parmasMap.put("MinDate",minDate);
        parmasMap.put("MaxDate",maxDate);
        TechniqueDto techniqueDto=null;
        StringBuilder sb=new StringBuilder("TSDatas/");
        sb.append(assetid).append("/").append(isOriginalData);
        try {
            String result=  MosHttpClient.requestGet(parmasMap,sb.toString());
            techniqueDto= JSON.parseObject(result, TechniqueDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return techniqueDto;
    }

    /**
     * 获取报警事件列表
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/AlarmEvents?MinDate={MinDate}&MaxDate={MaxDate}
     */
    @Override
    public List<AlarmEventDto> getAlarmEvents(String minDate, String maxDate) {
        Map<String,String> parmasMap=new HashMap<>(2);
        parmasMap.put("MinDate",minDate);
        parmasMap.put("MaxDate",maxDate);
        List<AlarmEventDto> alarmEventDtos=new ArrayList<>();
        StringBuilder sb=new StringBuilder("AlarmEvents/");
        try {
            String result=  MosHttpClient.requestGet(parmasMap,sb.toString());
            alarmEventDtos= JSONArray.parseArray(result, AlarmEventDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return alarmEventDtos;
    }

    /**
     * 报警事件获取报警详情
     * @param eventId 报警事件ID
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/AlarmEventDetail/{EventID}
     */
    @Override
    public AlarmEventDeatil getAlarmEventDetail(String eventId) {
        AlarmEventDeatil alarmEventDeatil=null;
        StringBuilder sb=new StringBuilder("AlarmEventDetail/");
        sb.append(eventId);
        try {
            String result=  MosHttpClient.requestGet(null,sb.toString());
            alarmEventDeatil= JSON.parseObject(result, AlarmEventDeatil.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return alarmEventDeatil;
    }

    /**
     * 时间范围获取报警详情列表
     * @param minDate
     * @param maxDate
     * @return
     * http://127.0.0.1:8125/api/EPMMOS/AlarmDetails?MinDate={MinDate}&MaxDate={MaxDate}
     */
    @Override
    public List<AlarmEventDeatil> getAlarmEventDetais(String minDate, String maxDate) {
        Map<String,String> parmasMap=new HashMap<>(2);
        parmasMap.put("MinDate",minDate);
        parmasMap.put("MaxDate",maxDate);
        List<AlarmEventDeatil> alarmEventDeatils=new ArrayList<>();
        StringBuilder sb=new StringBuilder("AlarmDetails/");
        try {
            String result=  MosHttpClient.requestGet(parmasMap,sb.toString());
            alarmEventDeatils= JSONArray.parseArray(result, AlarmEventDeatil.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return alarmEventDeatils;
    }

    /**
     * 转换波形视图数据
     * @param waveFromDto
     * @return
     */
    private List<WaveDataVO> processData (WaveFromDto waveFromDto){
        List<WaveDataVO> result = new ArrayList<>();
        List<Float> dataResult = waveFromDto.getYData();
        Float xInterval = waveFromDto.getXInterval();
        for (int i = 0; i < dataResult.size(); i++) {
            if (null != dataResult.get(i) && 0 != dataResult.get(i)) {
                WaveDataVO resultData = new WaveDataVO();
                resultData.setInterval(i * xInterval);
                resultData.setValue(dataResult.get(i));

                result.add(resultData);
            }
        }
        return result;
    }


}
